import React, { FC, useEffect, useState } from "react";
import type { ChangeEvent } from "react";
import { useNavigate, useLocation, useSearchParams } from "react-router-dom";
import { Input } from "antd";
import { LIST_SEARCH_PARAM_KEY } from "../constant";

const { Search } = Input;
const ListSearch: FC = () => {
  const nav = useNavigate();
  const { pathname } = useLocation();
  const [value, setValue] = useState("");
  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    setValue(event.target.value);
    console.log(value)
  }
  //获取URL 参数，并设置到input value
  const [searchParams] = useSearchParams();
  useEffect(() => {
    const curVal = searchParams.get(LIST_SEARCH_PARAM_KEY) || '';
    setValue(curVal);
  }, [searchParams]);

  function handleSearch(value: string) {
    //跳转页面 ，增加url 参数
    nav({
      pathname,
      search: `${LIST_SEARCH_PARAM_KEY}=${value}`, //丢掉其他的URL 参数
    });
  }
  return (
    <>
      <Search
        placeholder="请输入关键字"
        onSearch={handleSearch}
        style={{ width: "200px" }}
        onChange={handleChange}
        allowClear
      />
    </>
  );
};
export default ListSearch;
